import {  useMemoizedFn, } from 'ahooks';
import {createContext, Key, useEffect, useRef, useState} from 'react';
import {TNodesScrollPosition, TOffScreen, TOutlet} from '@/components/KeepAliveOutlet/type';

const useActivity = (props: TOffScreen) => {
	const {action, location, outlet} = props;
	const [outlets, setOutlets] = useState<TOutlet[]>([]);
	const {pathname, key} = location ?? {};
	const topRef = useRef<number>();
	const cacheNodeRef = useRef<HTMLDivElement | undefined | null>(undefined);
	const cacheNodesScrollRef = useRef<TNodesScrollPosition[] | undefined>(undefined);


	useEffect(() => {
		setOutlets((prev) => {
			if (!prev) return prev
			const index = prev.findIndex((v) => v.key === key);
			console.log(index);
			const initItem: TOutlet = {
				scrollOffset: 0, key, pathname, outlet,
			};
			if (action === 'REPLACE') {
				return [initItem];
			}
			if (index < 0) {
				return [...(prev ?? []), initItem];
			}
			if (action !== 'POP') {
				return [...(prev?.filter((v) => v.key !== key) ?? []), initItem];
			}
			cacheNodeRef.current = prev[index]?.compRef;
			return prev;
		});
		return () => {
			const cacheScrollNodes = cacheNodesScrollRef.current;
			const compRef = cacheNodeRef.current;
			setOutlets((prev) => {
				if (!prev) return  prev
				const index = prev.findIndex((v) => v.key === key);
				cacheNodesScrollRef.current = undefined;
				cacheNodeRef.current = undefined;
				if (index !== -1) {
					return prev?.map((v) => v.key === key ? {
						...v, scrollOffset: topRef.current ?? 0, cacheScrollNodes, compRef,
					} : v,);
				}
				return prev;
			});
		};
	}, [pathname, key]);


	const registryCompScroll = useMemoizedFn((node, isPopOver = true) => {
		cacheNodeRef.current = isPopOver ? node?.parentNode?.parentNode : node;
	});

	return {outlets, registryCompScroll, key};
};

export default useActivity;

export type TzOffScreenBack = {
	registryCompScroll: (ref: HTMLDivElement | null, isPopOver?: boolean) => void; outlets: any; key: Key;
};

export const OffScreenContext = createContext<TzOffScreenBack>({
	registryCompScroll: () => null,
	outlets: null,
	key: '',
});
